package com.bootdo.common.utils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SortUtils {
	/**	
	 * 对字符串进行字典序排序
	 * urlencode 是否对urlencode
	 * isLowerCase 是否转换大小写
	 * is pingjie 是否对url 用 = 和 & 连接
	 * @param paraMap
	 * @param urlencode
	 * @param isLowerCase
	 * @return
	 * @throws SDKRuntimeException
	 */
	public static String FormatBizQueryParaMap(HashMap<String, String> paraMap,
			boolean urlencode,boolean  isLowerCase,boolean isPingjie)  {

		String buff = "";
		try {
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(
					paraMap.entrySet());

			Collections.sort(infoIds,
					new Comparator<Map.Entry<String, String>>() {
						@Override
						public int compare(Map.Entry<String, String> o1,
								Map.Entry<String, String> o2) {
							return (o1.getKey()).toString().compareTo(
									o2.getKey());
						}
					});

			for (int i = 0; i < infoIds.size(); i++) {
				Map.Entry<String, String> item = infoIds.get(i);
				if (item.getKey() != "") {
					
					String key = item.getKey();
					String val = item.getValue();
					if (urlencode) {
						val = URLEncoder.encode(val, "utf-8");

					}
					if(isLowerCase){
						
						if(isPingjie) {
							if( i ==   (infoIds.size()-1)) {
								buff += key.toLowerCase() + "=" + val;
							}else {
								buff += key.toLowerCase() + "=" + val + "&";
							}
							
						}else {
							buff += key.toLowerCase()+val;
						}
						
					}else{
						if(isPingjie) {
							if( i ==   (infoIds.size()-1)) {
								buff += key + "=" + val;
							}else {
								buff += key + "=" + val + "&";
							}
							
						}else {
							buff += key + val;
						}
						
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return buff;
	}
}	
